package com.ado.abyss.core.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.ado.abyss.core.params.page.PageRequest;
import com.ado.abyss.core.params.page.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ado.abyss.core.dal.model.SysUser;
import com.ado.abyss.core.dal.model.SysUserRole;
import com.ado.abyss.core.manager.SysUserManager;
import com.ado.abyss.core.service.SysMenuService;
import com.ado.abyss.core.service.SysUserRoleService;
import com.ado.abyss.core.service.SysUserService;

@Service(value = "sysUserService")
public class SysUserServiceImpl implements SysUserService{

	@Autowired
	@Qualifier(value = "sysUserManager")
	private SysUserManager userManager ;
	@Autowired
	@Qualifier(value = "sysMenuService")
	private SysMenuService sysMenuService ;
	@Autowired
	@Qualifier(value = "sysUserRoleService")
	private SysUserRoleService sysUserRoleService ;

	
	@Override
	public SysUser findByName(String username) {
		SysUser sysUser = userManager.findByName(username) ;
		return sysUser;
	}

	@Override
	public Set<String> findPermissions(String name) {
		Set<String> perms = userManager.findPermissions(name) ;
		return perms;
	}

	@Override
	public SysUser getById(Long id) {
		return userManager.getByUserId(id);
	}

	@Override
	@Transactional
	public boolean save(SysUser record) {
		return userManager.saveUser(record);
	}


	@Override
	@Transactional
	public boolean delete(List<SysUser> records) {
		List<Long> ids = new ArrayList<Long>() ;
		if(records.size() > 0) {
			for (SysUser sysUser : records) {
				ids.add(sysUser.getId()) ;
			}
		}
		return userManager.deleteByIds(ids);
	}

	@Override
	public List<SysUserRole> findUserRoles(Long userId) {
		return userManager.findUserRoles(userId);
	}

	@Override
	public PageResult findPage(PageRequest pageRequest) {
		PageHelper.startPage(pageRequest.getPageNum() , pageRequest.getPageSize()) ;
		List<SysUser> sysUsers = userManager.findAll() ;
		PageInfo<SysUser> pageInfo = new PageInfo<>(sysUsers) ;
		PageResult pageResult = convertToResult(pageInfo) ;
		return pageResult ;
	}

	@Override
	public List<SysUser> findAll() {
		return userManager.findAll();
	}

	/**
	 *
	 * @param pageInfo
	 * @return
	 */
	private PageResult convertToResult(PageInfo<SysUser> pageInfo) {
		PageResult pageResult = new PageResult();
		pageResult.setPageSize(pageInfo.getPageSize());
		pageResult.setPageNum(pageInfo.getPageNum());
		pageResult.setContent(pageInfo.getList());
		pageResult.setTotalPages(pageInfo.getPages());
		pageResult.setTotalSize(pageInfo.getSize());
		return pageResult ;
	}
}
